package com.cl.pile.rule.func;

import com.alibaba.fastjson.JSONObject;
import com.cl.pile.rule.process.RuleMatcher;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author chenyitao
 * @date 2021/6/8
 */
public class AvgFunc extends NumBaseFunc {


    @Override
    public Object func(List<Object> data, String rootVar, Object root, JSONObject ruleJson, RuleMatcher ruleMatcher) {
        AtomicInteger size = new AtomicInteger(0);
        BigDecimal sum = numFuncCb(new BigDecimal(0), data, ruleJson, ruleMatcher, rootVar, root,
                (oldNum, dataValue) -> {
                    size.addAndGet(1);
                    return oldNum.add(dataValue);
                });
        return sum.divide(new BigDecimal(size.get()), 2, RoundingMode.DOWN).toString();
    }

    @Override
    public String funcName() {
        return "计算平均值";
    }
}
